package im

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"sync"

	"mall/service/forum/api/internal/biz/chat"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"

	"github.com/gorilla/websocket"
	"github.com/zeromicro/go-zero/core/logx"
)

type ImLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 添加售后申请
func NewImLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ImLogic {
	return &ImLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ImLogic) Im(req *types.ImReq, w http.ResponseWriter, r *http.Request) (resp *types.ImResp, err error) {
	if req.UserId == 0 {
		return nil, fmt.Errorf("invalid user id")
	}
	wg := &sync.WaitGroup{}
	userId := req.UserId
	upgrader := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println(err)
		return nil, nil
	}
	client := chat.NewChatClient(conn, strconv.FormatUint(userId, 10))
	wg.Add(2)
	go client.WritePump(wg)
	go client.ReadPump(wg)
	wg.Wait()
	return &types.ImResp{
		Msg: "连接成功",
	}, nil
}
